/*
 * 
 */
package lik.http.videoplay.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * 
 * @author <A HREF="mailto:li_kan@vobile.cn">Licey</A> 2012-2-24
 * 
 */
public class MediaFileService {
	private String path;
	private String suffx;
	private static List<File> medias;
	private static MediaFileService mediaFileService;

	public static MediaFileService initMediaFileService(String path) {
		mediaFileService = new MediaFileService();
		mediaFileService.path = path;
		mediaFileService.suffx = "mp4";
		mediaFileService.searchMediaFiles();
		return mediaFileService;
	}

	public static MediaFileService getMediaFileService() {
		return mediaFileService;
	}

	private MediaFileService() {

	}

	public List<File> searchMediaFiles() {
		File pathDir = new File(path);
		medias = mediaFileFromDir(pathDir);
		return medias;
	}

	private List<File> mediaFileFromDir(File dir) {
		List<File> mediaList = new ArrayList<File>();

		for (File file : dir.listFiles()) {
			if (file.isDirectory()) {
				mediaList.addAll(mediaFileFromDir(file));
			} else if (accept(file)) {
				mediaList.add(file);
			}
		}
		return mediaList;
	}

	private boolean accept(File pathname) {
		String temp = fileTypeFromFile(pathname);
		return suffx.indexOf(temp) > -1;
	}

	private String fileTypeFromFile(File pathname) {
		return pathname.getName().substring(pathname.getName().lastIndexOf(".") + 1);
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getSuffx() {
		return suffx;
	}

	public void setSuffx(String suffx) {
		this.suffx = suffx;
	}

	public List<File> getMedias() {
		return medias;
	}

	public void setMedias(List<File> medias) {
		this.medias = medias;
	}
}
